<template>
  <view class="withdraw-records-container">
	  <status-bar></status-bar>
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="goBack">
        <image src="/static/images/icon/backward_flat.png" class="back-icon-img"></image>
      </view>
      <view class="nav-title">提现记录</view>
    </view>
    
    <!-- 时间区间选择 -->
    <view class="date-picker-container">
      <uni-datetime-picker
        v-model="dateRange"
        type="daterange"
        rangeSeparator="至"
        @change="dateRangeChange"
        :border="false"
        :clearIcon="true"
        :start="startDate"
        :end="endDate"
        startPlaceholder="开始日期"
        endPlaceholder="结束日期"
      />
    </view>
    
    <!-- 提现记录列表（带下拉刷新和上拉加载） -->
    <scroll-view 
      scroll-y 
      class="withdraw-list"
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
      refresher-background="#f5f5f5"
    >
      <view class="record-item" v-for="(record, index) in withdrawRecords" :key="index">
        <view class="record-info">
          <view class="record-amount">申请金额: {{record.amount}}</view>
          <view class="record-date">{{record.date || record.time}}</view>
        </view>
        <view class="record-status" :class="getStatusClass(record.status)">
          {{record.status || '待审批'}}
          <view class="record-reason" v-if="record.reason">{{record.reason}}</view>
        </view>
      </view>
      
      <!-- 加载状态 -->
      <view class="loading-state">
        <uni-load-more :status="loadMoreStatus"></uni-load-more>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import uniLoadMore from '@/uni_modules/uni-load-more/components/uni-load-more/uni-load-more.vue'
import { getList } from '@/api/app/master/applylog.js'

export default {
  components: {
    uniLoadMore
  },
  onLoad() {
    // 页面加载时获取提现记录数据
    this.loadRecords();
  },
  data() {
    const currentDate = new Date()
    const currentYear = currentDate.getFullYear()
    const currentMonth = currentDate.getMonth() + 1
    
    // 计算默认的日期范围：当前月的第一天到最后一天
    const firstDay = new Date(currentYear, currentMonth - 1, 1)
    const lastDay = new Date(currentYear, currentMonth, 0)
    
    const formatDate = (date) => {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    }
    
    // 设置可选日期范围
    const startDate = '2020-01-01'
    const endDate = formatDate(new Date())
    
    return {
      dateRange: [formatDate(firstDay), formatDate(lastDay)], // 默认选择当前月
      startDate: startDate, // 可选日期范围开始
      endDate: endDate, // 可选日期范围结束
      currentPage: 1,
      pageSize: 10,
      total: 0,
      isRefreshing: false, // 是否正在下拉刷新
      loadMoreStatus: 'more', // 加载更多状态：more-加载前，loading-加载中，noMore-没有更多了
      withdrawRecords: [
        
      ]
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    
    // 格式化状态
    formatStatus(status) {
      // 根据后端返回的状态码转换为显示文本
      const statusMap = {
        1: '待审批',
        2: '通过',
        3: '驳回',
        0: '撤销'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 获取状态样式类
    getStatusClass(status) {
      switch(status) {
        case '待审批':
          return 'status-pending';
        case '通过':
          return 'status-approved';
        case '撤销':
          return 'status-cancelled';
        case '驳回':
          return 'status-rejected';
        default:
          return '';
      }
    },
    
    // 日期区间选择变更
    dateRangeChange(dateRange) {
      if (!dateRange || !dateRange.length) return;
      
      console.log('选择的日期区间:', dateRange);
      
      // 重置页码
      this.currentPage = 1;
      // 重新加载数据
      this.loadRecords(true);
    },
    
    // 下拉刷新
    onRefresh() {
      // 如果没有选择时间则不执行并且取消刷新
      if (!this.dateRange || !this.dateRange.length) {
        this.isRefreshing = false;
        return;
      }

      this.isRefreshing = true;
      this.currentPage = 1;
      this.loadRecords(true);
    },
    
    // 上拉加载更多
    loadMore() {
      if (this.loadMoreStatus !== 'more') return;
      
      this.currentPage++;
      this.loadMoreStatus = 'loading';
      this.loadRecords(false);
    },
    
    // 加载记录数据
    loadRecords(isReset = false) {
      if (!this.dateRange || !this.dateRange.length) return;
      
      // 如果不是刷新操作，则显示加载中
      if (!this.isRefreshing) {
        this.loadMoreStatus = 'loading';
      }
      
      // 构建请求参数
      const params = {
        startTime: this.dateRange[0],
        endTime: this.dateRange[1],
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };
      
      // 调用接口获取数据
      getList(params).then(res => {
        if (res.code === 200) {
          // 获取数据成功
          const records = res.rows || [];
          const total = res.total || 0;
          
          // 处理返回的数据
          const formattedRecords = records.map(item => {
            return {
              id: item.id,
              amount: item.applyAmount,
              date: item.applyTime,
              status: this.formatStatus(item.applyStatus),
              reason: item.approveremark || '',
              statusCode: item.applyStatus
            };
          });
          
          // 更新总数据量
          this.total = total;
          
          // 如果是重置数据（下拉刷新或日期变更），则替换数据
          if (isReset) {
            this.withdrawRecords = formattedRecords;
          } else {
            // 否则追加数据
            this.withdrawRecords = this.withdrawRecords.concat(formattedRecords);
          }
          
          // 判断是否还有更多数据
          if (this.withdrawRecords.length >= this.total) {
            this.loadMoreStatus = 'noMore';
          } else {
            this.loadMoreStatus = 'more';
          }
        } else {
          // 获取数据失败
          uni.showToast({
            title: res.msg || '获取提现记录失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        console.error('获取提现记录失败:', err);
        uni.showToast({
          title: '获取提现记录失败，请稍后重试',
          icon: 'none'
        });
      }).finally(() => {
        // 结束下拉刷新状态
        if (this.isRefreshing) {
          this.isRefreshing = false;
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.withdraw-records-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 90rpx;
  background-color: #4c9bfb;
  color: #fff;
  padding: 0 30rpx;
  position: relative;
}

.back-btn {
  position: absolute;
  left: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon-img {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
}

/* 日期选择区域 */
.date-picker-container {
  background-color: #fff;
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1px solid #eee;
}

/* 提现记录列表 */
.withdraw-list {
  background-color: #fff;
  height: calc(100vh - 240rpx);
  padding: 0 30rpx;
}

/* 提现记录项 */
.record-item {
  display: flex;
  justify-content: space-between;
  padding: 30rpx 0;
  border-bottom: 1px solid #eee;
}

.record-item:last-child {
  border-bottom: none;
}

.record-info {
  display: flex;
  flex-direction: column;
}

.record-amount {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.record-date {
  font-size: 24rpx;
  color: #999;
}

.record-status {
  font-size: 28rpx;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.status-pending {
  color: #f39c12;
}

.status-approved {
  color: #2ecc71;
}

.status-cancelled {
  color: #7f8c8d;
}

.status-rejected {
  color: #e74c3c;
}

.record-reason {
  font-size: 24rpx;
  color: #999;
  margin-top: 5rpx;
}

/* 加载状态 */
.loading-state {
  padding: 20rpx 0;
}
</style>